-- ============================================
-- ROCKET CASINO - MACHINE A SOUS
-- Le COMPUTER est le jeu : connexion au clavier physique, puis jeu
-- entierement a la souris (clics), avec une interface visuelle
-- inspiree d'une machine a sous classique dans un style Team Rocket.
-- Le MONITOR n'affiche QUE la Poke Ball Team Rocket qui tourne, en
-- boucle, jamais touchee, jamais utilisee pour jouer.
--
-- Fichier requis dans le meme dossier : client_solde.lua
-- ============================================

local bank = dofile("client_solde.lua")
math.randomseed(os.epoch and os.epoch("utc") or os.time())

local BET_MIN, BET_MAX, BET_STEP = 1, 20, 1

-- Decalage fin des sprites de symboles dans leur case (ajuste ici si
-- besoin, positif = vers le bas/la droite, negatif = vers le haut/la gauche)
local SPRITE_OFFSET_X = 1
local SPRITE_OFFSET_Y = 1

-- Verifie qu'une valeur est bien une vraie constante colors.xxx
-- (puissance de 2 entre 1 et 32768) avant de l'envoyer a colors.toBlit,
-- pour eviter tout plantage si une couleur invalide se glisse quelque
-- part (ex: pixel corrompu d'un fichier .nfp).
local function isValidColor(c)
    if type(c) ~= "number" or c <= 0 then return false end
    local n = math.log(c, 2)
    return math.abs(n - math.floor(n + 0.5)) < 0.0001 and c <= 32768
end

-- ============================================
-- PARTIE 1 : POKE BALL DECORATIVE SUR LE MONITOR
-- ============================================

local function buildBannerLoop()
    local mon = peripheral.find("monitor")
    if not mon then
        return nil -- pas de moniteur branche : on continue sans deco
    end

    mon.setTextScale(0.5)
    mon.setBackgroundColor(colors.black)
    mon.clear()
    local mw, mh = mon.getSize()

    local FRAME_DELAY = 0.1
    local ROTATION_SPEED = 0.22

    local function newCanvas(bg)
        local c = {}
        for y = 1, mh do
            c[y] = {}
            for x = 1, mw do
                c[y][x] = { bg = bg, ch = " ", fg = colors.white }
            end
        end
        return c
    end

    local function px(canvas, x, y, bg, ch, fg)
        x, y = math.floor(x + 0.5), math.floor(y + 0.5)
        if x >= 1 and x <= mw and y >= 1 and y <= mh then
            local cell = canvas[y][x]
            if bg then cell.bg = bg end
            if ch then
                cell.ch = ch
                cell.fg = fg or cell.fg
            end
        end
    end

    local function render(canvas)
        local toBlit = colors.toBlit
        for y = 1, mh do
            local row = canvas[y]
            local chars, fgs, bgs = {}, {}, {}
            for x = 1, mw do
                local cell = row[x]
                chars[x] = cell.ch
                local fg = isValidColor(cell.fg) and cell.fg or colors.white
                local bg = isValidColor(cell.bg) and cell.bg or colors.black
                fgs[x] = toBlit(fg)
                bgs[x] = toBlit(bg)
            end
            mon.setCursorPos(1, y)
            mon.blit(table.concat(chars), table.concat(fgs), table.concat(bgs))
        end
    end

    local function fillEllipse(canvas, cx, cy, rx, ry, color)
        if rx <= 0 or ry <= 0 then return end
        for y = math.floor(cy - ry), math.ceil(cy + ry) do
            local dy = (y - cy) / ry
            local t = 1 - dy * dy
            if t >= 0 then
                local dx = rx * math.sqrt(t)
                for x = math.floor(cx - dx), math.ceil(cx + dx) do
                    px(canvas, x, y, color)
                end
            end
        end
    end

    local R_PATTERN = { "####.", "#...#", "#...#", "####.", "#..#.", "#...#", "#...#" }

    local function drawGlyphR(canvas, x0, y0, scale, color)
        for row = 1, #R_PATTERN do
            local line = R_PATTERN[row]
            for col = 1, #line do
                if line:sub(col, col) == "#" then
                    for sy = 0, scale - 1 do
                        for sx = 0, scale - 1 do
                            px(canvas, x0 + (col - 1) * scale + sx, y0 + (row - 1) * scale + sy, color)
                        end
                    end
                end
            end
        end
    end

    local function drawPokeball(canvas, cx, cy, r, angle)
        local squish = math.max(0.12, math.abs(math.cos(angle)))
        local rx = r * squish
        local ry = r

        fillEllipse(canvas, cx, cy, rx + 1.2, ry + 1.2, colors.gray)

        for y = math.floor(cy - ry), math.ceil(cy + ry) do
            local dy = (y - cy) / ry
            local t = 1 - dy * dy
            if t >= 0 then
                local dx = rx * math.sqrt(t)
                local color
                if y < cy - ry * 0.08 then
                    color = colors.black
                elseif y > cy + ry * 0.08 then
                    color = colors.red
                else
                    color = colors.lightGray
                end
                for x = math.floor(cx - dx), math.ceil(cx + dx) do
                    px(canvas, x, y, color)
                end
            end
        end

        for x = math.floor(cx - rx), math.ceil(cx + rx) do
            px(canvas, x, cy, colors.black)
        end

        local buttonR = math.max(1, r * 0.28 * squish)
        fillEllipse(canvas, cx, cy, buttonR + 0.6, buttonR + 0.6, colors.black)
        fillEllipse(canvas, cx, cy, buttonR, buttonR, colors.white)
        fillEllipse(canvas, cx, cy, buttonR * 0.5, buttonR * 0.5, colors.lightGray)

        if squish > 0.55 then
            local scale = math.max(1, math.floor(r * squish / 5))
            local rx0 = math.floor(cx - 2 * scale)
            local ry0 = math.floor(cy - ry * 0.75)
            for dx = -1, 1 do
                for dy = -1, 1 do
                    if dx ~= 0 or dy ~= 0 then
                        drawGlyphR(canvas, rx0 + dx, ry0 + dy, scale, colors.black)
                    end
                end
            end
            drawGlyphR(canvas, rx0, ry0, scale, colors.red)
        end
    end

    return function()
        local angle = 0
        local cx, cy = math.floor(mw / 2), math.floor(mh / 2)
        local r = math.floor(math.min(mw, mh) * 0.4)
        while true do
            local canvas = newCanvas(colors.black)
            drawPokeball(canvas, cx, cy, r, angle)
            render(canvas)
            angle = angle + ROTATION_SPEED
            sleep(FRAME_DELAY)
        end
    end
end

-- ============================================
-- PARTIE 2 : LE JEU, SUR L'ECRAN DU COMPUTER (clavier pour le login,
-- puis 100% a la souris)
-- ============================================

local W, H = term.getSize()

-------------------------------
-- OUTILS DE DESSIN BAS NIVEAU (canvas pixel + blit, sur le terminal)
-------------------------------

local function newCanvas(bg)
    local c = {}
    for y = 1, H do
        c[y] = {}
        for x = 1, W do
            c[y][x] = { bg = bg, ch = " ", fg = colors.white }
        end
    end
    return c
end

local function px(canvas, x, y, bg, ch, fg)
    x, y = math.floor(x + 0.5), math.floor(y + 0.5)
    if x >= 1 and x <= W and y >= 1 and y <= H then
        local cell = canvas[y][x]
        if bg then cell.bg = bg end
        if ch then
            cell.ch = ch
            cell.fg = fg or cell.fg
        end
    end
end

local function render(canvas)
    local toBlit = colors.toBlit
    for y = 1, H do
        local row = canvas[y]
        local chars, fgs, bgs = {}, {}, {}
        for x = 1, W do
            local cell = row[x]
            chars[x] = cell.ch
            local fg = isValidColor(cell.fg) and cell.fg or colors.white
            local bg = isValidColor(cell.bg) and cell.bg or colors.black
            fgs[x] = toBlit(fg)
            bgs[x] = toBlit(bg)
        end
        term.setCursorPos(1, y)
        term.blit(table.concat(chars), table.concat(fgs), table.concat(bgs))
    end
end

local function fillEllipse(canvas, cx, cy, rx, ry, color)
    if rx <= 0 or ry <= 0 then return end
    for y = math.floor(cy - ry), math.ceil(cy + ry) do
        local dy = (y - cy) / ry
        local t = 1 - dy * dy
        if t >= 0 then
            local dx = rx * math.sqrt(t)
            for x = math.floor(cx - dx), math.ceil(cx + dx) do
                px(canvas, x, y, color)
            end
        end
    end
end

local function fillRect(canvas, x1, y1, x2, y2, color)
    for y = y1, y2 do
        for x = x1, x2 do
            px(canvas, x, y, color)
        end
    end
end

local function fillTriangleUp(canvas, cx, baseY, tipY, halfWidth, color)
    local height = baseY - tipY
    if height <= 0 then return end
    for y = tipY, baseY do
        local f = (y - tipY) / height
        local w = halfWidth * f
        for x = math.floor(cx - w), math.ceil(cx + w) do
            px(canvas, x, y, color)
        end
    end
end

local function fillTriangleDown(canvas, cx, baseY, tipY, halfWidth, color)
    local height = tipY - baseY
    if height <= 0 then return end
    for y = baseY, tipY do
        local f = (tipY - y) / height
        local w = halfWidth * f
        for x = math.floor(cx - w), math.ceil(cx + w) do
            px(canvas, x, y, color)
        end
    end
end

local function fillTriangleSide(canvas, baseX, tipX, cy, halfHeight, color)
    local width = tipX - baseX
    if width == 0 then return end
    local step = width > 0 and 1 or -1
    for x = baseX, tipX, step do
        local f = (x - baseX) / width
        local hh = halfHeight * (1 - f)
        for y = math.floor(cy - hh), math.ceil(cy + hh) do
            px(canvas, x, y, color)
        end
    end
end

-------------------------------
-- MINI POLICE PIXEL 5x7
-------------------------------

local FONT = {
    R = { "####.", "#...#", "#...#", "####.", "#..#.", "#...#", "#...#" },
    T = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "..#.." },
}

local function drawGlyph(canvas, pattern, x0, y0, scale, color)
    for row = 1, #pattern do
        local line = pattern[row]
        for col = 1, #line do
            if line:sub(col, col) == "#" then
                for sy = 0, scale - 1 do
                    for sx = 0, scale - 1 do
                        px(canvas, x0 + (col - 1) * scale + sx, y0 + (row - 1) * scale + sy, color)
                    end
                end
            end
        end
    end
end

local function drawText(canvas, x, y, text, fg, bg)
    for i = 1, #text do
        px(canvas, x + i - 1, y, bg, text:sub(i, i), fg)
    end
end

-------------------------------
-- SYMBOLES : vrais sprites .nfp (format Paint de CC:Tweaked), charges une
-- fois au demarrage et centres dans chaque case au moment de dessiner.
-------------------------------

local SPRITE_FILES = {
    BALL = "ball.nfp",
    THUNDER = "thunder.nfp",
    CLAW = "claw.nfp",
    LEAF = "leaf.nfp",
    FLAME = "flame.nfp",
}

local SPRITE_IMAGES = {}
for id, path in pairs(SPRITE_FILES) do
    if fs.exists(path) then
        local ok, img = pcall(paintutils.loadImage, path)
        if ok then SPRITE_IMAGES[id] = img end
    end
end

-- repli (si un .nfp manque) : caractere colore, comme avant
local CHIP_CHAR = { THUNDER = "Z", CLAW = "w", LEAF = "v", FLAME = "^", BALL = "@" }
local CHIP_FG = { THUNDER = colors.yellow, CLAW = colors.white, LEAF = colors.lime, FLAME = colors.red, BALL = colors.red }

local function blitSpriteCentered(canvas, image, boxX1, boxY1, boxX2, boxY2)
    local imgH = #image
    local imgW = 0
    for _, row in ipairs(image) do imgW = math.max(imgW, #row) end
    local cx = math.floor((boxX1 + boxX2) / 2)
    local cy = math.floor((boxY1 + boxY2) / 2)
    local startX = cx - math.floor(imgW / 2) + SPRITE_OFFSET_X
    local startY = cy - math.floor(imgH / 2) + SPRITE_OFFSET_Y
    for row = 1, imgH do
        local line = image[row]
        if line then
            for col = 1, imgW do
                local color = line[col]
                -- on ignore silencieusement tout pixel dont la couleur
                -- n'est pas une vraie constante colors.xxx (fichier .nfp
                -- corrompu ou mal cree hors du programme "paint")
                if color and isValidColor(color) then
                    px(canvas, startX + col - 1, startY + row - 1, color)
                end
            end
        end
    end
end

local function drawSymbolBlock(canvas, id, x1, y1, x2, y2)
    -- fond garanti quoi qu'il arrive, pour que la case ne soit jamais vide
    fillRect(canvas, x1, y1, x2, y2, colors.black)
    local image = SPRITE_IMAGES[id]
    if image then
        blitSpriteCentered(canvas, image, x1, y1, x2, y2)
    else
        local cx = math.floor((x1 + x2) / 2)
        local cy = math.floor((y1 + y2) / 2)
        px(canvas, cx, cy, nil, CHIP_CHAR[id] or "?", CHIP_FG[id] or colors.white)
    end
end

-------------------------------
-- TABLE DES GAINS
-------------------------------

local SYMBOLS = {
    { id = "BALL",    weight = 1, mult = 20 },
    { id = "THUNDER", weight = 2, mult = 10 },
    { id = "CLAW",    weight = 3, mult = 7 },
    { id = "FLAME",   weight = 4, mult = 5 },
    { id = "LEAF",    weight = 5, mult = 3 },
}

local TOTAL_WEIGHT = 0
for _, s in ipairs(SYMBOLS) do TOTAL_WEIGHT = TOTAL_WEIGHT + s.weight end

local MULT_BY_ID = {}
for _, s in ipairs(SYMBOLS) do MULT_BY_ID[s.id] = s.mult end

local function pickSymbol()
    local roll = math.random(TOTAL_WEIGHT)
    local acc = 0
    for _, s in ipairs(SYMBOLS) do
        acc = acc + s.weight
        if roll <= acc then return s.id end
    end
    return SYMBOLS[#SYMBOLS].id
end

local function evaluateWin(symbols, bet)
    if symbols[1] == symbols[2] and symbols[2] == symbols[3] then
        local mult = MULT_BY_ID[symbols[1]] or 1
        return bet * mult, "JACKPOT ! 3x " .. symbols[1] .. " (x" .. mult .. ")"
    elseif symbols[1] == symbols[2] or symbols[2] == symbols[3] or symbols[1] == symbols[3] then
        return bet, "Petit gain, mise remboursee !"
    else
        return 0, "Perdu... retente ta chance !"
    end
end

-------------------------------
-- ECRAN DE JEU (compteurs LCD, fenetres de rouleaux, badges,
-- indicateurs de rotation) - style Team Rocket original
-------------------------------

local function drawStripedBorder(canvas)
    for x = 1, W do
        local colTop = ((x + 1) % 4 < 2) and colors.red or colors.yellow
        local colBot = ((x + 1) % 4 < 2) and colors.red or colors.yellow
        px(canvas, x, 1, colTop)
        px(canvas, x, H, colBot)
    end
    for y = 1, H do
        local colL = ((y + 1) % 4 < 2) and colors.red or colors.yellow
        local colR = ((y + 1) % 4 < 2) and colors.red or colors.yellow
        px(canvas, 1, y, colL)
        px(canvas, W, y, colR)
    end
end

local function drawGameScreen(player, credit, lastGain, bet, reels, message, lockedCount)
    local canvas = newCanvas(colors.black)

    -- bordure striee rouge/jaune tout autour de l'ecran, style Team Rocket
    drawStripedBorder(canvas)

    -- 2/3 gauche = rouleaux sur toute la hauteur, 1/3 droite = titre /
    -- compteurs / mise, en bas = message (1 ligne de marge avant la bordure)
    local msgY = H - 1
    local playY1, playY2 = 3, H - 3

    local leftX2 = math.floor(W * 2 / 3)
    local rightX1 = leftX2 + 2

    -- === COLONNE DE GAUCHE : les 3 rouleaux, pleine hauteur ===
    local reelGap = math.max(1, math.floor(W * 0.015))
    local reelsAreaW = leftX2 - 2
    local colW = math.max(3, math.floor((reelsAreaW - 2 * reelGap) / 3))

    local rowH = math.max(2, math.floor((playY2 - playY1 + 1) / 3))
    local rowKeys = { "top", "mid", "bot" }

    for i = 1, 3 do
        local x1 = 3 + (i - 1) * (colW + reelGap)
        local x2 = x1 + colW - 1

        -- contour de toute la colonne : garantit qu'elle reste visible
        -- meme si un symbole individuel a un probleme d'affichage
        fillRect(canvas, x1 - 1, playY1 - 1, x2 + 1, playY2 + 1, colors.yellow)
        fillRect(canvas, x1, playY1, x2, playY2, colors.black)

        for r = 1, 3 do
            local y1 = playY1 + (r - 1) * rowH
            local y2 = math.max(y1, (r == 3) and playY2 or (y1 + rowH - 2))
            drawSymbolBlock(canvas, reels[i][rowKeys[r]], x1, y1, x2, y2)
        end
    end

    -- === COLONNE DE DROITE : titre, compteurs, mise ===
    local rightW = (W - 1) - rightX1
    local ry = playY1

    local function rightLine(text, fg, bg)
        if bg then fillRect(canvas, rightX1, ry, W - 2, ry, bg) end
        drawText(canvas, rightX1, ry, text, fg, bg)
        ry = ry + 1
    end

    local function boldTitleLine(text)
        fillRect(canvas, rightX1, ry, W - 2, ry, colors.yellow)
        for i = 1, #text do
            local fg = (i == 1) and colors.red or colors.black
            px(canvas, rightX1 + i - 1, ry, nil, text:sub(i, i), fg)
        end
        ry = ry + 1
    end

    boldTitleLine("ROCKET")
    boldTitleLine("SLOTS")
    ry = ry + 1

    -- CREDIT et GAIN sur fond blanc, bien visibles
    rightLine("CREDIT", colors.gray, colors.black)
    rightLine(tostring(credit), colors.black, colors.white)
    ry = ry + 1


    -- === BOUTONS : plus visuels, 2 lignes de haut avec un espace entre eux ===
    local buttons = {}
    local function rightButton(id, label, bg, fg)
        fillRect(canvas, rightX1, ry, W - 2, ry + 1, bg)
        local text = label
        if #text > rightW then text = text:sub(1, rightW) end
        local textY = ry + math.floor(1 / 2)
        local textX = rightX1 + math.max(0, math.floor((rightW - #text) / 2))
        drawText(canvas, textX, textY, text, fg or colors.white, bg)
        table.insert(buttons, { id = id, x1 = rightX1, x2 = W - 2, y1 = ry, y2 = ry + 1 })
        ry = ry + 3 -- 2 lignes de bouton + 1 ligne d'espace
    end

    rightButton("BET_DOWN", "- MISE", colors.red, colors.white)
    rightButton("BET_UP", "+ MISE", colors.green, colors.white)
    rightButton("SPIN", "TOURNER x" .. bet, colors.yellow, colors.red)
    rightButton("QUIT", "QUITTER", colors.gray, colors.red)

    -- message en bas, pleine largeur (au-dessus de la bordure)
    local msgX = math.max(2, math.floor((W - #message) / 2) + 1)
    drawText(canvas, msgX, msgY, message, colors.yellow, colors.black)

    render(canvas)
    return buttons
end

local function spinAnimation(player, creditDuringSpin, bet)
    local reels = {}
    for i = 1, 3 do
        reels[i] = { top = pickSymbol(), mid = pickSymbol(), bot = pickSymbol() }
    end
    local stopTicks = { 10, 16, 22 }
    local maxTick = stopTicks[3]

    for tick = 1, maxTick do
        local lockedCount = 0
        for i, reel in ipairs(reels) do
            if tick <= stopTicks[i] then
                reel.top = reel.mid
                reel.mid = reel.bot
                reel.bot = pickSymbol()
            else
                lockedCount = lockedCount + 1
            end
        end
        drawGameScreen(player, creditDuringSpin, "...", bet, reels, "Ca tourne...", lockedCount)
        sleep(0.06)
    end

    return reels
end

local function runGameSession(player)
    local credit = bank.getBalance(player)
    local bet = BET_MIN
    local lastGain = 0
    local message = "Place ta mise et lance les rouleaux !"
    local reels = {
        { top = "LEAF", mid = "LEAF", bot = "LEAF" },
        { top = "LEAF", mid = "LEAF", bot = "LEAF" },
        { top = "LEAF", mid = "LEAF", bot = "LEAF" },
    }
    local playing = true

    while playing do
        credit = bank.getBalance(player)
        local buttons = drawGameScreen(player, credit, lastGain, bet, reels, message, nil)

        local _, _, x, y = os.pullEvent("mouse_click")
        local pressed = nil
        for _, b in ipairs(buttons) do
            if x >= b.x1 and x <= b.x2 and y >= b.y1 and y <= b.y2 then
                pressed = b.id
                break
            end
        end

        if pressed == "BET_DOWN" then
            bet = math.max(BET_MIN, bet - BET_STEP)
        elseif pressed == "BET_UP" then
            bet = math.min(BET_MAX, bet + BET_STEP)
        elseif pressed == "SPIN" then
            if credit < bet then
                message = "Solde insuffisant !"
            else
                local newBal, err = bank.addBalance(player, -bet)
                if not newBal then
                    message = err or "Erreur banque, reessaie."
                else
                    reels = spinAnimation(player, newBal, bet)
                    local gain, resultMsg = evaluateWin({ reels[1].mid, reels[2].mid, reels[3].mid }, bet)
                    if gain > 0 then
                        bank.addBalance(player, gain)
                    end
                    lastGain = gain
                    message = resultMsg
                    credit = bank.getBalance(player)
                end
            end
        elseif pressed == "QUIT" then
            playing = false
        end
    end
end

-------------------------------
-- CONNEXION AU CLAVIER PHYSIQUE (texte simple, avant le visuel)
-------------------------------

local function centerTextLine(y, text, fg)
    term.setBackgroundColor(colors.black)
    term.setTextColor(fg or colors.white)
    local x = math.max(1, math.floor((W - #text) / 2) + 1)
    term.setCursorPos(x, y)
    term.write(text)
end

local function authenticateKeyboard()
    term.setBackgroundColor(colors.black)
    term.clear()
    centerTextLine(2, "=== ROCKET CASINO ===", colors.red)
    term.setCursorPos(1, 4)
    term.setTextColor(colors.white)
    term.write("Pseudo Minecraft : ")
    local username = read()

    while true do
        term.setTextColor(colors.white)
        term.write("Mot de passe : ")
        local password = read("*")
        local ok, err = bank.authenticate(username, password)
        if ok then
            return username
        else
            term.setTextColor(colors.red)
            print(err or "Erreur de connexion, reessaie.")
        end
    end
end

local function loginThenPlayLoop()
    while true do
        local player = authenticateKeyboard()
        runGameSession(player)
    end
end

-------------------------------
-- LANCEMENT : Poke Ball deco sur le moniteur + jeu sur le computer
-------------------------------

local bannerLoop = buildBannerLoop()

if bannerLoop then
    parallel.waitForAll(bannerLoop, loginThenPlayLoop)
else
    loginThenPlayLoop()
end
